<template>
  <view class="filter-date-container">
    <!-- 日期显示和筛选按钮 -->
    <view class="date-filter-bar">
      <view class="date-display" @click="showDatePicker">
        <text class="date-text">{{ currentDateText }}</text>
        <uni-icons type="down" size="16" color="#666"></uni-icons>
      </view>
    </view>
  </view>

  <!-- 日期选择弹窗 -->
  <uni-popup
    ref="popupRef"
    type="bottom"
    background-color="#fff"
    @change="change"
  >
    <view class="date-picker-container">
      <view class="picker-header">
        <text class="title">月份选择</text>
        <uni-icons type="closeempty" size="16" color="#666"></uni-icons>
      </view>
      <picker-view
        :value="pickerValue"
        @change="pickerChange"
        class="picker-view"
      >
        <picker-view-column>
          <view class="picker-item" v-for="(year, index) in years" :key="index">
            {{ year }}年
          </view>
        </picker-view-column>
        <picker-view-column>
          <view
            class="picker-item"
            v-for="(month, index) in months"
            :key="index"
          >
            {{ month }}月
          </view>
        </picker-view-column>
      </picker-view>
      <view class="btm">
        <view
          class="btn color-#8e8e8e border-1 border-#8e8e8e"
          @click="cancelPicker"
          >重置</view
        >
        <view class="btn color-#fff bg-#ffb200" @click="confirmPicker"
          >确定</view
        >
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import { dateUtils } from "@/utils/dayjs.js";
import dayjs from "dayjs";

// 获取当前年月
const now = dayjs();
const currentYear = now.year();
const currentMonth = now.month() + 1; // dayjs的月份是0-11，需要+1

// 当前选中的日期（默认显示当前年月）
const currentDate = ref({
  year: currentYear,
  month: currentMonth,
});

// 弹窗引用
const popupRef = ref(null);

// 生成年份数组（从5年前到当前年，从小到大排列）
const years = computed(() => {
  const yearArray = [];
  for (let i = currentYear - 5; i <= currentYear; i++) {
    yearArray.push(i);
  }
  return yearArray;
});

// 当前选中的年份索引（默认为当前年，即数组最后一个）
const selectedYearIndex = ref(5);

// 生成月份数组（根据选中的年份动态生成）
const months = computed(() => {
  const selectedYear = years.value[selectedYearIndex.value];
  const monthArray = [];

  // 如果选中的是当前年，只能选择到当前月
  if (selectedYear === currentYear) {
    for (let i = 1; i <= currentMonth; i++) {
      monthArray.push(i);
    }
  } else {
    // 历史年份可以选择全部12个月
    for (let i = 1; i <= 12; i++) {
      monthArray.push(i);
    }
  }

  return monthArray;
});

// picker-view 的值（初始化为当前年月）
const pickerValue = ref([5, currentMonth - 1]); // 5是当前年的索引，currentMonth - 1是月份索引

// 当前日期文本显示
const currentDateText = computed(() => {
  const text = `${currentDate.value.year}-${String(
    currentDate.value.month
  ).padStart(2, "0")}`;
  console.log("计算日期文本:", currentDate.value, "结果:", text);
  return text;
});

// 显示日期选择器
const showDatePicker = () => {
  // 同步 pickerValue 到当前日期
  const yearIndex = years.value.findIndex(
    (year) => year === currentDate.value.year
  );
  const monthIndex = currentDate.value.month - 1;

  selectedYearIndex.value = yearIndex !== -1 ? yearIndex : 5;

  // 确保月份索引在有效范围内
  const validMonthIndex = Math.min(monthIndex, months.value.length - 1);
  pickerValue.value = [selectedYearIndex.value, Math.max(0, validMonthIndex)];

  popupRef.value.open("bottom");
};

// picker 值改变
const pickerChange = (e) => {
  const newValue = e.detail.value;
  const oldYearIndex = selectedYearIndex.value;
  const newYearIndex = newValue[0];

  // 如果年份改变了
  if (oldYearIndex !== newYearIndex) {
    selectedYearIndex.value = newYearIndex;

    // 检查当前选中的月份在新年份下是否有效
    const newMonths = months.value;
    const currentMonthIndex = newValue[1];

    // 如果当前月份索引超出了新年份的月份范围，重置为最后一个月
    if (currentMonthIndex >= newMonths.length) {
      pickerValue.value = [newYearIndex, newMonths.length - 1];
    } else {
      pickerValue.value = newValue;
    }
  } else {
    pickerValue.value = newValue;
  }

  console.log("picker值改变:", {
    newValue,
    selectedYearIndex: selectedYearIndex.value,
    months: months.value.length,
  });
};

// 取消选择
const cancelPicker = () => {
  // 重置为当前选中的值
  pickerValue.value = [
    years.value.findIndex((year) => year === currentDate.value.year),
    currentDate.value.month - 1,
  ];
  popupRef.value.close();
};

// 确认选择
const confirmPicker = async () => {
  const yearIndex = pickerValue.value[0];
  const monthIndex = pickerValue.value[1];
  const selectedYear = years.value[yearIndex];
  const selectedMonth = months.value[monthIndex];

  console.log("确认选择:", {
    pickerValue: pickerValue.value,
    yearIndex,
    monthIndex,
    selectedYear,
    selectedMonth,
    years: years.value,
    months: months.value,
  });

  // 确保选中的值有效
  if (selectedYear !== undefined && selectedMonth !== undefined) {
    // 使用解构赋值确保响应式更新
    currentDate.value.year = selectedYear;
    currentDate.value.month = selectedMonth;

    await nextTick();

    console.log("更新后的日期:", currentDate.value);
    console.log("更新后的文本:", currentDateText.value);

    // 触发日期变更事件
    emit("dateChange", { ...currentDate.value });
  }

  popupRef.value.close();
};

// 筛选按钮点击
const handleFilter = () => {
  emit("filter", currentDate.value);
};

// 弹窗状态变更
const change = (e) => {
  console.log("popup change:", e);
};

// 定义事件
const emit = defineEmits(["dateChange", "filter"]);

onMounted(() => {
  // 初始化 pickerValue 的正确索引
  const yearIndex = years.value.findIndex(
    (year) => year === currentDate.value.year
  );
  const monthIndex = currentDate.value.month - 1;

  selectedYearIndex.value = yearIndex !== -1 ? yearIndex : 5;

  // 确保月份索引在有效范围内
  const validMonthIndex = Math.min(monthIndex, months.value.length - 1);
  pickerValue.value = [selectedYearIndex.value, Math.max(0, validMonthIndex)];

  // 初始化时触发一次日期变更事件，传递对象副本避免引用共享
  emit("dateChange", { ...currentDate.value });
});
</script>

<style scoped lang="scss">
.date-filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.date-display {
  display: flex;
  align-items: center;
  gap: 10rpx;
  cursor: pointer;
}

.date-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.filter-button {
  padding: 10rpx 24rpx;
  background-color: #f8f8f8;
  border-radius: 20rpx;
  cursor: pointer;
}

.filter-text {
  font-size: 28rpx;
  color: #666;
}

// 日期选择器弹窗样式
.date-picker-container {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
  padding-bottom: 100rpx;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 40rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.cancel-btn,
.confirm-btn {
  font-size: 32rpx;
  color: #007aff;
  cursor: pointer;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
}

.picker-view {
  height: 400rpx;
  padding: 0 40rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 68rpx;
  font-size: 32rpx;
  color: #333;
}
.btm {
  display: flex;
  justify-content: space-between;
  padding: 0 60rpx 20rpx;

  .btn {
    text-align: center;
    border-radius: 50rpx;
    padding: 10rpx 100rpx;
    font-weight: bold;
  }
}
</style>
